package com.iphanta.community.common;

import com.iphanta.community.common.utils.ApplicationContextUtils;
import com.iphanta.community.common.utils.RedisKey;
import com.iphanta.community.common.utils.RedisKeyUtils;
import com.iphanta.community.common.utils.ResultUtils;
import com.iphanta.community.remote.service.VerifyTokenService;
import io.netty.buffer.ByteBuf;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 墨声 E-mail: zehong.hongframe.huang@gmail.com
 * create time: 3/8/22 5:24 PM
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    public final static String USER_ID = "USER_ID";
    public final static String AUTHORIZATION_TOKEN = "AUTHORIZATION_TOKEN";
    public final static String DEBUG = "DEBUG";
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationInterceptor.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uid = request.getHeader(USER_ID);
        String token = request.getHeader(AUTHORIZATION_TOKEN);


        if(Objects.nonNull(request.getHeader("PRINT_REQUEST"))) {
            String test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

            LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> {}", StringEscapeUtils.unescapeHtml4(test));
            LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> {}", test);
        }

        if (StringUtils.isBlank(uid)) {
            throw new BusinessException("USER_ID不能为空", ResultUtils.FAIL_ON_BUSINESS.result());
        }
        String debug = request.getHeader(DEBUG);
        if (!Objects.equals(debug, "true")) {
            if (StringUtils.isBlank(token)) {
                throw new BusinessException("未登陆", ResultUtils.FAIL_ON_BUSINESS.result());
            }
            String tokenKey = RedisKeyUtils.INSTANCE.key(RedisKey.VALUE_TOKEN, token);
            String v = this.redisTemplate.opsForValue().get(tokenKey);
            UserUtils.setUid(v);
            if(Objects.isNull(v)) {
                VerifyTokenService verifyTokenService = ApplicationContextUtils.getBean(VerifyTokenService.class);
                verifyTokenService.verifyToken(uid, token);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtils.remove();
    }
}
